<script src="../../api/system/user.js"></script>
<template>
  <div>
    <h2>员工信息</h2>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="el-form" :title="title" >
<!--    <el-form :title="title"  ref="form" :model="form" label-width="120px" >-->

      <el-form-item label="图片上传" >
        <el-upload
          v-model="form.picture"
          :on-success="onUploadSuccess"
          :before-upload="beforeUpload"
          :on-preview="onUploadPreview"
          :on-remove="onUploadRemove"
          :multiple="true"
          :action="BASE_API+'/pricture/fileUpload'"
          class="upload-demo"
          list-type="picture-card"
          :file-list="fileList">
          <i class="el-icon-plus"/>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过2MB</div>
        </el-upload>
        <el-image
          :src="form.picture"
          style="width: 150px;height:150px;left: 170px;top: -0px;position: absolute"
        ></el-image>
      </el-form-item>

      <el-form-item label="员工ID" prop="employeeId">
        <el-input v-model="form.employeeId" placeholder="请输入员工ID" />
      </el-form-item>

          <el-form-item label="账号" prop="employeeAccount">
            <el-input v-model="form.employeeAccount" placeholder="请输入员工账号" />
          </el-form-item>
          <el-form-item label="初始登录密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入初始登录密码" />
          </el-form-item>
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" />
          </el-form-item>
      <el-form-item label="所属部门">
        <div class="app-container">
          <el-select
            class="main-select-tree"
            ref="selectTree"
            :v-model="form.department"
            style="width: 300px;"
            name='option 1'>

            <!-- otion 1 -->
            <el-option
              v-for="item in optionData(cityData)"
              :label="item.label"
              :value="item.value"
              style="display: none;"/>

            <el-tree
              class="main-select-el-tree"
              ref="selectelTree"
              :data="cityData"
              :props='treeProps'
              highlight-current
              @node-click="handleNodeClick"
              :expand-on-click-node="expandOnClickNode"
              default-expand-all />
          </el-select>
        </div>
      </el-form-item>

      <el-form-item label="所属角色">
        <el-select v-model="form.role" placeholder="请选择">
          <el-option v-for="item in roleList" :label="item.roleName" :value="item.roleId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="员工状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="启用"></el-radio>
          <el-radio label="禁用"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="beizhu">
        <el-input v-model="form.beizhu" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
  </div>
</template>
<script>
import { addEmployee, getEmployee, updateEmployee } from "@/api/employee/employee";
import {deptTreeSelect} from "@/api/system/user";
import {listRole} from "@/api/system/role";
export default {
  data() {
    return {

      selectValue: '',
      expandOnClickNode: true,
      options: [],
      treeProps: {
        children: 'children',
        label: 'label'
      },
      cityData: [
        {
          id: 1,
          label: '七尾集团',
          children: [
            {
              id: 2,
              label: '客服部',
              children: [
                { id: 3, label: '客服1组' },
                { id: 4, label: '客服2组' }
              ]
            },
            {
              id: 5,
              label: '市场部',
              children: [
                { id: 6, label: '市场1组' },
                { id: 7, label: '市场2组' }
              ]
            },
            {
              id: 8,
              label: '财务部',
              children: [
                { id: 9, label: '财务1组' },
                { id: 10, label: '财务2组' }
              ]
            }
          ]
        }
      ],



      status: '',
      // 接口API地址
      BASE_API: 'http://localhost:8702',
      form: {},
      // empPosterList: [],
      empImagesList: [],
      empAttrValueList: [],
      checkAll: false,
      role: [],
      // cities: cityOptions,
      isIndeterminate: true,
      employeeStatus: false ,// 初始状态为禁用
      //弹出标题
      title: "",
      fileList: [],
      // 图片预览对话框
      dialogImageVisible: false,
      // 表单校验
      rules: {

        employeeAccount: [
          { required: true, message: "员工账号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "初始登录密码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        department: [
          { required: true, message: "所属部门不能为空", trigger: "blur" }
        ],
        role: [
          { required: true, message: "所属角色不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "员工状态不能为空", trigger: "change" }
        ],
        creator: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        creationTime: [
          { required: true, message: "创建时间                                                                                                                                                           不能为空", trigger: "blur" }
        ],

      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      roleList:[],
    };
  },
  computed: {
    employeeStatusText() {
      return this.employeeStatus ? '启用' : '禁用';
    },
    formNoNewline: {
      get() {
        return {
          qyNameNoNewline: this.form.qyName.replace(/\n/g, ''),
          qyCodeNoNewline: this.form.qyCode.replace(/\n/g, ''),
          contactNameNoNewline: this.form.contactName.replace(/\n/g, ''),
          contactPhoneNoNewline: this.form.contactPhone.replace(/\n/g, ''),
          addressNoNewline: this.form.address.replace(/\n/g, ''),
          remarksNoNewline: this.form.remarks.replace(/\n/g, '')
        };
      },
      set(value) {
        this.form.qyName = value.qyNameNoNewline;
        this.form.qyCode = value.qyCodeNoNewline;
        this.form.contactName = value.contactNameNoNewline;
        this.form.contactPhone = value.contactPhoneNoNewline;
        this.form.address = value.addressNoNewline;
        this.form.remarks = value.remarksNoNewline;
      }
    }
  },
  created() {
    console.log( this.$route.query.id+"....."+(this.$route.query.id!==undefined))
    if(this.$route.query.id!==undefined){
      this.findEmployee();
      this.fileList = this.form.picture;
    }else {
      this.form = {}
    }
    this.sysUser();
    //所属部门动态获取
    // deptTreeSelect().then(response => {
    //   this.deptOptions = response.data;
    //   console.log(this.deptOptions)
    // });
  },
  methods: {
    sysUser(){
      listRole().then(response => {
        this.roleList = response.rows;
      })
    },
    /**
     * 树形转平面的迭代方法
     * option 1的el-option需要此方法绑定数据
     */
    optionData(array, result=[]) {
      array.forEach(item => {
        result.push({label:item.label,value:item.id})
        if (item.children && item.children.length !== 0) {
          this.optionData(item.children, result)
        }
      })
      return JSON.parse(JSON.stringify(result))
    },

    // 点击节点的响应
    handleNodeClick(node) {
      this.form.department = node.label;
      this.$refs.selectTree.blur();
      console.log(node.label);
    },


    // //角色动态获取（有问题
    // user(){
    //   listRole().then(response => {
    //     this.roleList = response.data
    //   })
    // },

    //修改获取id回显
    findEmployee(){
      var id = this.$route.query.id;
      getEmployee(id).then(response => {
        this.form = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleroleChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 删除上传的文件
    onUploadRemove(file, fileList) {
      var list = []
      this.empImagesList.forEach(item => {
        if(file.url != item.imgUrl) {
          list.push(item)
        }
      })
      this.empImagesList = list
    },
    // 上传图片成功的回调
    onUploadSuccess(res, file) {
      console.log(res,file);
      this.form.picture = res;
      // 填充上传文件列表
      this.empImagesList.push({
        imgName: file.name,
        imgUrl: file.response.data
      })
    },
    // 文件上传限制条件
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    // 上传的文件预览
    onUploadPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    /** 提交按钮 */
    submitForm() {
      const attrListArray = []
      this.empAttrValueList = attrListArray
      if (this.empImagesList.length > 0) {
        this.imgUrl = this.empImagesList[0].imgUrl
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEmployee(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$router.push({ path: '/employeeindex'})
            });
          } else {
            this.empAttrValueList = attrListArray
            if (this.empImagesList.length > 0) {
              this.imgUrl = this.empImagesList[0].imgUrl
            }
            addEmployee(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$router.push({ path: '/employeeindex'})
            });
          }
        }
      });
    },
    handleRemove(file) {
      console.log(file);
    },
  },
};
</script>






<style scoped>
.main-select-el-tree .el-tree-node .is-current>.el-tree-node__content {
  font-weight: bold;
  color: #409eff;
}

.main-select-el-tree .el-tree-node.is-current>.el-tree-node__content {
  font-weight: bold;
  color: #409eff;
}
.dialog-footer {
  position: relative; /* 确保容器是相对的，以便内部元素可以绝对定位 */
  display: flex;      /* 使用flex布局来水平排列按钮 */
  justify-content: flex-end; /* 将内容推到右边 */
  align-items: flex-end;     /* 将内容推到下边（虽然在这个例子中可能不需要，因为默认就是底部） */
  height: 50px;              /* 根据需要调整高度 */
  padding: 10px;             /* 根据需要调整内边距 */
  box-sizing: border-box;    /* 确保内边距和边框不会增加额外的高度 */
}

.dialog-footer .el-button {
  margin-left: 10px; /* 在按钮之间添加一些间距 */
}
/* 设置整个表单容器的样式 */
.el-form {
  width: 80%; /* 根据需要调整宽度 */
  margin: 0 auto; /* 居中 */
  padding: 20px; /* 内边距 */
  border: 1px solid #dcdcdc; /* 边框 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 阴影 */
}

/* 设置表单项的样式 */
.el-form-item {
  margin-bottom: 20px; /* 每个表单项之间的间距 */
}

/* 设置输入框的样式 */
.el-input__inner {
  border: 1px solid #c0c4cc; /* 边框颜色 */
  border-radius: 4px; /* 圆角 */
  padding: 10px; /* 内边距 */
  font-size: 14px; /* 字体大小 */
  box-sizing: border-box; /* 包括内边距和边框在内计算宽度 */
  width: 100%; /* 宽度占满父容器 */
}

/* 设置上传组件的样式 */
.el-upload__input {
  border: none; /* 去掉边框 */
  padding: 0; /* 去掉内边距 */
  width: 100%; /* 宽度占满父容器 */
  height: auto; /* 高度自适应 */
}

/* 设置图片预览对话框的样式 */
.el-dialog {
  width: 80%; /* 对话框宽度 */
  margin: 0 auto; /* 居中 */
}

.el-dialog__header {
  background-color: #f5f7fa; /* 头部背景色 */
  padding: 15px 20px; /* 内边距 */
  border-bottom: 1px solid #ebeef5; /* 底部边框 */
}

.el-dialog__body {
  padding: 20px; /* 内边距 */
}

/* 图片预览的样式 */
.el-dialog img {
  max-width: 100%; /* 图片最大宽度占满对话框 */
  height: auto; /* 高度自适应 */
  display: block; /* 去除底部间隙 */
  margin: 0 auto; /* 居中 */
}

/* 按钮的样式 */
.el-button {
  padding: 10px 20px; /* 内边距 */
  font-size: 14px; /* 字体大小 */
  border-radius: 4px; /* 圆角 */
}

.el-button--primary {
  background-color: #409eff; /* 背景色 */
  border-color: #409eff; /* 边框色 */
  color: #fff; /* 文字颜色 */
}

.el-button--primary:hover {
  background-color: #66b1ff; /* 悬停背景色 */
  border-color: #66b1ff; /* 悬停边框色 */
}
</style>

